<template>
  <div class="comment-item" :class="{ 'sub-comment-item': !isTopComment }">
    <div class="comment-item-avatar">
      <img :src="comment.createUserHead || defaultImg" alt="">
    </div>
    <div class="comment-item-main">
      <p class="comment-item-top">
        <span class="comment-item-name">
          <template v-if="isOpenData && comment.createUserStaffId">
            <open-data type="userName" :openid="comment.createUserStaffId"></open-data>
          </template>
          <template v-else>
            {{ comment.createUserName || ''}}
          </template>
        </span>
        <span class="comment-item-reply-name" v-if="!isTopComment">
          {{$t('common.base.reply')}}
          <span class="comment-item-name">
            <template v-if="isOpenData && comment.replyUserStaffId">
              <open-data type="userName" :openid="comment.replyUserStaffId"></open-data>
            </template>
            <template v-else>
              {{ comment.replyUserName || ''}}
            </template>
          </span>：
        </span>
        <span class="time-show">
          {{ comment.createTime | fmt_datetime }}
        </span>
      </p>
      <p class="comment-item-content">
        <biz-comment-html :html="comment.content.replace(/\[[\u4E00-\u9FA5]{1,3}\]/gi, emotion)"></biz-comment-html>
      </p>
      <div class="comment-item-operation status-view" v-if="!useForShare">
        <span class="status-view-each" @click="toReply()">
          <i class="iconfont icon-pinglun" @click="addComment()"></i>
          <b v-if="!replying">{{$t('common.base.reply')}}</b>
          <b v-else>{{$t('common.base.cancelReply')}}</b>
        </span>
        <span
          @click="deleteComment()"
          class="status-view-each"
          v-loading="deleteLoading"
          v-if="allowDelete || initData.userInfo.userId === comment.createUser">
          <i class="iconfont icon-delete"></i>
          <b>{{$t('wiki.detail.component.comment.des1')}}</b>
        </span>
      </div>
      <div class="comment-reply" v-if="replying && !useForShare">
        <!-- <el-input
          ref="replyInput"
          class="replyContent"
          @focus="replyInputFocus()"
          @blur="inputBlur()"
          :placeholder="isOpenData ? '回复' :`回复${comment.createUserName || ''}`"
          v-model="replyContent"
          type="textarea">
        </el-input> -->
        <biz-at-textarea class="biz-at-textarea" ref="replyInput" search-url="/message/user/lists" name-key="displayName" v-model="replyContent" :at-users.sync="atUsers">
          <template slot="item" slot-scope="item">
            <img :src="head(item.user.head)">
            <span>{{item.user.displayName}}</span>
          </template>
          <textarea class="base-at-textarea" @focus="replyInputFocus()" @input="inputContent" :placeholder="isOpenData ? $t('common.base.reply') :`${$t('common.base.reply')}${comment.createUserName || ''}`" maxlength="1000" :rows="2" @blur="inputBlur()"></textarea>
        </biz-at-textarea>
        <common-emoji
          ref="commonEmoji"
          :input-ref="$refs.replyInput"
          @changeInput="value => replyContent = value">
        </common-emoji>
       
      </div>
      <div class="flex-x jus-end mar-t-16">
        <el-button
          type="primary"
          v-show="replyContentFocus"
          v-loading="addLoading"
          @click="addComment()"
          class="send-btn">
          {{$t('common.base.comment')}}
        </el-button>
      </div>
      
      <slot name="subComment" />
    </div>
    <hr class="sub-comment-item-line" v-if="!isTopComment">
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
import { addComment, deleteComment } from '@src/api/Repository'
import { getOssUrl } from '@src/util/assets'
import commonEmoji from '@src/component/emoji'
import {enCodeAtText} from '@src/util/atText'
import { cutAtTextContent } from 'pub-bbx-utils'
import { useTenantId } from '@hooks/useRootWindow.ts';
import { safeNewDate } from '@src/util/time';

const defaultImg = getOssUrl('/avatar.png')

export default {
  name: 'comment-item',
  components: {
    [commonEmoji.name]: commonEmoji
  },
  props: {
    replayTo: {

    },
    comment: {
      type: Object
    },
    initData: {
      type: Object
    },
    isTopComment: {
      type: Boolean,
      default: false
    },
    useForShare: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      isOpenData,
      recommendData: [],

      replyContent: '',
      replying: false,

      defaultImg,
      replyContentFocus: false,

      deleteLoading: false,
      addLoading: false,

      ifEmojiShow: false,

      replyContentTimeout: void 0,
      atUsers:[]
    }
  },
  mounted() {
    this.wikiId && this.getOtherWiki()
  },
  watch: {
    wikiId() {
      this.getOtherWiki()
    }
  },
  computed: {
    // 拥有评论管理权限
    allowDelete() {
      return this.initData?.userInfo?.authorities?.INFO_DELETE_COMMENT
    },
    refsss() {
      return this.$refs
    }
  },
  methods: {
    head(src){
      if(!src) return defaultImg;
      return src;
    },
    replyInputFocus() {
      this.replyContentFocusChange(true)
    },
    inputBlur() {
      this.replyContentFocusChange(false)
    },
    replyContentFocusChange(focus) {
      // 考虑到点击表情时短暂的失焦以及再聚焦，需要清除定时
      this.replyContentTimeout && clearTimeout(this.replyContentTimeout)
      if (focus) {
        this.replyContentFocus = true
      } else {
        // 延时是考虑到点击评论按钮
        this.replyContentTimeout = setTimeout(() => {
          this.replyContentFocus = false
        }, 300)
      }
    },
    // 将匹配结果替换表情图片
    emotion (res) {
      let word = res.replace(/\[|\]/gi, '')
      const list = ['微笑', '撇嘴', '色', '发呆', '得意', '流泪', '害羞', '闭嘴', '睡', '大哭', '尴尬', '发怒', '调皮', '呲牙', '惊讶', '难过', '酷', '冷汗', '抓狂', '吐', '偷笑', '可爱', '白眼', '傲慢', '饥饿', '困', '惊恐', '流汗', '憨笑', '大兵', '奋斗', '咒骂', '疑问', '嘘', '晕', '折磨', '衰', '骷髅', '敲打', '再见', '擦汗', '抠鼻', '鼓掌', '糗大了', '坏笑', '左哼哼', '右哼哼', '哈欠', '鄙视', '委屈', '快哭了', '阴险', '亲亲', '吓', '可怜', '菜刀', '西瓜', '啤酒', '篮球', '乒乓', '咖啡', '饭', '猪头', '玫瑰', '凋谢', '示爱', '爱心', '心碎', '蛋糕', '闪电', '炸弹', '刀', '足球', '瓢虫', '便便', '月亮', '太阳', '礼物', '拥抱', '强', '弱', '握手', '胜利', '抱拳', '勾引', '拳头', '差劲', '爱你', 'NO', 'OK', '爱情', '飞吻', '跳跳', '发抖', '怄火', '转圈', '磕头', '回头', '跳绳', '挥手', '激动', '街舞', '献吻', '左太极', '右太极']
      let index = list.indexOf(word)
      return `<img src="/resource/images/emoji/${index}.gif" align="middle">`   
    },
    toReply() {
      if (this.replying) {
        this.replying = false
        this.replyContent = ''
      } else {
        this.replying = true
      }
    },
    addComment() {
      !this.replyContent && this.$platform.notification({
        title: this.$t('wiki.detail.component.comment.tips1'),
        type: 'warning'
      })
      let replyContent = enCodeAtText(this.replyContent, this.atUsers);
      let receivers = []
      this.atUsers.forEach(item=>{
        if(this.replyContent.indexOf(`${item.displayName} `) > -1){
          receivers.push(item.userId)
        }
      })
      let receiversString = receivers.join(',')    
      let query = ''
      if(this.atUsers.length > 0){
        let queryData = {
          receivers:receiversString,
          tenantId: useTenantId().value,
          content: cutAtTextContent(this.replyContent),
          sendUserName: this.initData?.userInfo?.displayName,
          bizId: this.comment.wikiId,
          bizNo: this.title
        };
        query = '?';
        for (let i in queryData) {
          query += `&${i}=${queryData[i]}`;
        }
      }
      this.addLoading = true
      addComment({
        wikiId: this.comment.wikiId,
        content: replyContent,
        replyUser: this.comment.createUser,
        parentId: this.comment.id
      }, query).then(res => {
        if (res.code !== 0) {
          this.$platform.notification({
            title: res.message,
            type: 'error'
          })
          return
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.releaseSuccess'),
          type: 'success'
        })
        this.replyContent = ''
        this.atUsers = []
        this.$emit('refresh', this.comment)
        this.$emit('commentChange')
      }).catch(err => {
        console.log(err)
      })
        .finally(() => {
          this.addLoading = false
        })
    },
    async deleteComment() {
      if (!(await this.$platform.confirm(this.$t('common.base.tip.areYouSureYouWantDeletIt2')))) return
      this.deleteLoading = true
      deleteComment({
        id: this.comment.id,
        wikiId: this.comment.wikiId
      }).then(res => {
        if (res.code !== 0) {
          this.$platform.notification({
            title: res.message,
            type: 'error'
          })
          return
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.deleteSuccess'),
          type: 'success'
        })
        this.$emit('refresh', this.comment)
        this.$emit('commentChange')
      }).catch(err => {
        console.log(err)
      })
        .finally(() => {
          this.deleteLoading = false
        })
    },
    inputContent(event){
      let value = event.target.value;
      this.replyInput = value;
    },
  },
}
</script>

<style lang="scss" scoped>
.status-view {
  &-each {
    color: #595959;
    margin-right: 24px;
    font-size: 0;
    line-height: 20px;
    cursor: pointer;
  }
  b {
    font-size: 14px;
    font-weight: 400;
    vertical-align: middle;
  }
  .iconfont {
    font-size: 14px;
    font-weight: 400;
    vertical-align: middle;
    &:before {
      margin-right: 4px;
    }
  }
}

.comment-reply {
  display: flex;
  align-items: center;
  margin-top: 12px;
  position: relative;
  .send-btn {
    margin-left: 24px;
    align-items: center;
    // display: none;
  }
  .replyContent {
    flex: 1;
    // &:focus {
    //   &+.send-btn {
    //     display: block;
    //     flex-shrink: 0;
    //   }
    // }
  }
}
.comment-item {
  display: flex;
  padding-top: 16px;
  padding-bottom: 16px;
  &-main {
    flex: 1;
    width: 100%;
  }
}
.comment-item-top {
  line-height: 20px;
  // height: 20px;
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 400;
  color: #595959;
  line-height: 20px;
  .comment-item-name {
    font-size: 14px;
    font-weight: bold;
    color: #262626;
  }
  .time-show {
    float: right;
    font-size: 12px;
    font-weight: 400;
    color: #8C8C8C;
  }
}
.comment-item-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 12px;
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}
.comment-item-content {
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 400;
  color: #595959;
  line-height: 20px;
  word-break: break-all;
}
// .comment-item-operation {
//   margin-bottom: 16px;
// }
::v-deep .el-textarea__inner {
  min-height: 42px;
  padding: 10px 16px;
  height: 40px;
  font-size: 14px;
  font-weight: 400;
  color: #262626 !important;
  line-height: 20px;
  border-radius: 4px;
  background: #F5F5F5;
  border: 1px solid #E8E8E8;
  &::-webkit-input-placeholder{
    color: #8C8C8C;
  }
  &::-moz-placeholder{
    color: #8C8C8C;
  }
  &:-ms-input-placeholder{
    color: #8C8C8C;
  }
}
// .comment-item-operation {
//   margin-bottom: 12px;
// }

.sub-comment-item {
  // background: #F5F5F5;
  padding: 16px;
  position: relative;
  .comment-reply {
    margin-top: 12px;
  }
  ::v-deep .el-textarea__inner {
    background: #FFFFFF;
    border: 1px solid #E8E8E8;
    border-radius: 4px;
  }
}
.sub-comment-item-line {
  position: absolute;
  width: calc(100% - 32px);
  bottom: 0;
  margin: 0;
  color: #20ca20;
  border: 0;
  border-bottom: 1px solid #E5E6E5;
}
.isInputFocus {
  right: 91px;
}

.status-view-each {
  color: #8C8C8C;
}
</style>